from flask import render_template, g, redirect, request, jsonify, current_app, abort

from info import db, constants
from info.models import User, News, Category
from info.modules.profile import profile_blu
from info.utils.common import user_login_data
from info.utils.image_storage import storage
from info.utils.response_code import RET


@profile_blu.route('/other_news_list')
def other_news_list():
    """关注详情"""
    p = request.args.get('p',1)
    user_id = request.args.get('user_id')
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if not all([p, user_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    if not user:
        return jsonify(errno=RET.NODATA, errmsg="用户不存在")
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(p, constants.OTHER_NEWS_PAGE_MAX_COUNT, False)
        # 获取当前页数据
        news_li = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    news_dict_li = []

    for news_item in news_li:
        news_dict_li.append(news_item.to_review_dict())
    data = {"news_list": news_dict_li, "total_page": total_page, "current_page": current_page}
    return jsonify(errno=RET.OK, errmsg="OK", data=data)


@profile_blu.route('/other')
@user_login_data
def other():
    """查看其他用户信息"""
    user = g.user
    # 获取其他用户id
    user_id = request.args.get('id')
    if not user:
        abort(404)
    others = None
    try:
        others = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
    if not others:
        abort(404)
    # 判断当前用户是否关注过该用户
    is_followed = False
    if g.user:
        if others in g.user.followed:
            is_followed = True

    data = {
        'user_info': user.to_dict(),
        'other_info': others.to_dict(),
        'is_followed': is_followed
    }

    return render_template('news/other.html', data=data)


@profile_blu.route('/user_follow')
@user_login_data
def user_follow():
    """我的关注"""
    user = g.user
    p = request.args.get('p', 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    users = []
    current_page = 1
    total_page = 1
    try:
        paginate = user.followed.paginate(p, constants.USER_FOLLOWED_MAX_COUNT, False)
        users = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='数据库查询失败')
    user_dict_li = []
    for item in users:
        user_dict_li.append(item.to_dict())
    data = {
        "current_page": current_page,
        "total_page": total_page,
        "users": user_dict_li
    }

    return render_template('news/user_follow.html', data=data)


@profile_blu.route('/news_list')
@user_login_data
def news_list():
    p = request.args.get('p', 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    user = g.user
    news_li = []
    current_page = 1
    total_page = 1
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
        news_li = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
    news_dict_li = []
    for news in news_li:
        news_dict_li.append(news.to_review_dict())
    data = {
        'news_list': news_dict_li,
        'current_page': current_page,
        'total_page': total_page
    }

    return render_template('news/user_news_list.html', data=data)


@profile_blu.route('/news_release', methods=['GET', 'POST'])
@user_login_data
def news_release():
    """新闻发布"""
    if request.method == 'GET':
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DATAERR, errmsg='数据库查询失败')
        categories_li = []
        for category in categories:
            categories_li.append(category.to_dict())
        categories_li.pop(0)

        return render_template('news/user_news_release.html', data={"categories": categories_li})
    # 获取参数
    title = request.form.get('title')
    source = '个人发布'
    category_id = request.form.get('category_id')
    digest = request.form.get('digest')
    index_image = request.files.get('index_image')
    content = request.form.get('content')
    # 校验参数
    if not all([title, source, category_id, digest, index_image, content]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    try:
        category_id = int(category_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 读取图片
    try:
        image_url = index_image.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    # 图片上传到七牛云
    try:
        image_url = storage(image_url)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg='图片上传失败')

    # 创建模型对象
    news = News()
    news.title = title
    news.source = source
    news.category_id = category_id
    news.digest = digest
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + image_url
    news.user_id = g.user.id
    news.content = content
    news.status = 1

    # 将数据保存到数据库
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='数据保存失败')
    return jsonify(errno=RET.OK, errmsg='新闻发布成功，待审核')


@profile_blu.route('/user_collection')
@user_login_data
def user_collection():
    """我的收藏"""
    p = request.args.get('p', 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    user = g.user
    collections = []
    current_page = 1
    total_page = 1

    try:
        paginate = user.collection_news.paginate(p, constants.OTHER_NEWS_PAGE_MAX_COUNT, False)
        collections = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    collection_dict_li = []
    for collect in collections:
        collection_dict_li.append(collect.to_basic_dict())
    data = {
        "collections": collection_dict_li,
        "current_page": current_page,
        "total_page": total_page
    }

    return render_template('news/user_collection.html', data=data)


@profile_blu.route('/pass_info', methods=['GET', 'POST'])
@user_login_data
def pass_info():
    if request.method == 'GET':
        return render_template('news/user_pass_info.html')
    # 获取参数
    old_password = request.json.get('old_password')
    new_password = request.json.get('new_password')
    # 校验参数
    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    user = g.user
    if not user.check_passowrd(old_password):
        return jsonify(errno=RET.PARAMERR, errmsg='原密码输入错误')

    user.password = new_password
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='数据保存失败')
    return jsonify(errno=RET.OK, errmsg='操作成功')


@profile_blu.route('/pic_info', methods=['GET', 'POST'])
@user_login_data
def pic_info():
    user = g.user
    if request.method == 'GET':
        return render_template('news/user_pic_info.html', data={'user_info': user.to_dict()})
    # 获取文件
    try:
        avatar_file = request.files.get('avatar').read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.IOERR, errmsg='文件读写错误')
    # 上传七牛云
    try:
        key = storage(avatar_file)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(error=RET.THIRDERR, errmsg='上传七牛云失败')
    # 创建user模型

    user.avatar_url = key
    try:

        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DATAERR, errmsg='数据提交错误')
    return jsonify(errno=RET.OK, errmsg='操作成功', data={"avatar_url": constants.QINIU_DOMIN_PREFIX + key})


@profile_blu.route('/base_info', methods=['GET', 'POST'])
@user_login_data
def base_info():
    if request.method == 'GET':
        return render_template('news/user_base_info.html', data={'user_info': g.user.to_dict()})
    nick_name = request.json.get('nick_name')
    signature = request.json.get('signature')
    gender = request.json.get('gender')

    if not all([nick_name, signature, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    if gender not in ['MAN', 'WOMAN']:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    user = g.user
    user.nick_name = nick_name
    user.signature = signature
    user.gender = gender
    return jsonify(errno=RET.OK, errmsg='操作成功')


@profile_blu.route('/info')
@user_login_data
def user_info():
    user = g.user
    if not user:
        return redirect('/')
    data = {
        'user_info': user.to_dict()
    }
    return render_template('/news/user.html', data=data)
